<template>
  <Header />
  <Menu />
    <div v-if="showPageContent" class="container-fluid">
      <div class="row text-center justify-content-center webtitle"></div>
      <div class="row justify-content-center">
        <el-form ref="chapterForm" :model="form" label-width="auto" @submit.prevent="updateChapter" style="max-width: 90%;">
          <el-form-item label="小说名称：">
            <el-input v-model="info" clearable disabled></el-input>
          </el-form-item>
          <el-form-item label="章节标题：">
            <el-input v-model="form.chapter_title" clearable required></el-input>
          </el-form-item>
          <el-form-item label="章节内容：">
            <el-input type="textarea" v-model="form.chapter_content" :rows="contentRows" required></el-input>
          </el-form-item>
          <div class="twobtn">
            <el-button type="primary" native-type="submit">提交</el-button>
            <el-button type="success" @click="goToRead">阅读</el-button>
            <el-button @click="goBack">返回</el-button>
          </div>
        </el-form>


      </div>
    </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import { useRouter } from 'vue-router';
import axios from 'axios';
import { ElNotification } from 'element-plus';
import Header from "@/components/Header.vue";
import Menu from "@/components/Menu.vue";
import VueCookies from "vue-cookies";
import config from "../../../config/config.js";

const showPageContent = ref(true);
const router = useRouter();
const chapterId = parseInt(router.currentRoute.value.params.chapterId);
const form = ref({
  chapter_title: '',
  chapter_content: '',
  chapterId: chapterId,
});
const info = ref('');

const userToken = VueCookies.get('userToken');
const apiUrl = `${config.apiUrl}/novel-chapter/get?chapterId=${chapterId}`;
const headers = {
  Authorization: `Bearer ${userToken}`
};

const fetchChapterInfo = async () => {
  try {
    const response = await axios.get(apiUrl, { headers });
    if (response.status === 200) {
      const chapterInfo = response.data;
      form.value.chapter_title = chapterInfo.chapter_title;
      form.value.chapter_content = renderContent(chapterInfo.chapter_content);
      info.value = chapterInfo.novelInfo.novel_name;
    } else {
      showPageContent.value = false;
      ElNotification({
        message: '不存在该章，章节号有误！',
        type: 'error',
        duration: 2000
      });
    }
  } catch (error) {
    console.error('获取章节信息失败:', error);
    showPageContent.value = false;
    ElNotification({
      message: '章节号有误',
      type: 'error',
      duration: 2000
    });
  }
};

const updateChapter = async () => {
  const apiUrl = `${config.apiUrl}/novel-chapter/update`;
  try {
    const response = await axios.post(apiUrl, form.value, { headers });
    if (response.status === 200) {
      ElNotification({
        message: '章节更新成功！',
        type: 'success',
        duration: 2000
      });
    } else {
      ElNotification({
        message: response.data.message || '章节更新失败！',
        type: 'error',
        duration: 2000
      });
    }
  } catch (error) {
    console.error('章节更新失败:', error);
    ElNotification({
      message: '章节更新失败！',
      type: 'error',
      duration: 2000
    });
  }
};

const goBack = () => {
  router.back();
};

const renderContent = (content) => {
  if (!content) return '';
  // 替换 HTML 标签
  content = content.replace(/<br\s*\/?>/gi, '\n');
  content = content.replace(/&nbsp;/gi, ' ');
  return content;
};

const contentRows = computed(() => {
  if (!form.value.chapter_content) return 10; // 默认10行
  const rowCount = Math.ceil(form.value.chapter_content.length / 39); // 每行约40个字符
  return rowCount > 10 ? rowCount : 10; // 超过10行时显示所有行，否则显示10行
});
const goToRead = () =>{
  router.push('/chapter/' + chapterId);
}
onMounted(fetchChapterInfo);
</script>

<style scoped>
.webtitle {
  font-size: 15px;
  padding: 10px;
}
.twobtn{
  display: flex;
  justify-content: center;
  margin-bottom: 15px;
}
</style>
